<template>
  <div class="admin-group-visit">
    <div class="page-header">
      <h2>团体信息维护</h2>
      <div class="header-actions">
        <el-button type="primary" @click="openEdit()"><el-icon>
            <Plus />
          </el-icon>新增</el-button>
      </div>
    </div>

    <el-card>
      <div class="toolbar">
        <el-input v-model="keyword" placeholder="搜索团体/组织者" style="width: 240px" clearable />
        <el-select v-model="status" placeholder="状态" clearable style="width: 140px">
          <el-option label="待审核" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>
        <el-button @click="loadList" :loading="loading">查询</el-button>
        <el-button @click="exportExcel">导出</el-button>
      </div>

      <el-table :data="list" v-loading="loading" stripe>
        <el-table-column prop="groupName" label="团体机构名称" min-width="180" />
        <el-table-column prop="groupSize" label="预计参观人数" width="120" />
        <el-table-column prop="visitDate" label="预计参观日期" width="130" />
        <el-table-column prop="visitPurpose" label="关注产品" min-width="180" show-overflow-tooltip />
        <el-table-column prop="visitPurposeCheckout" label="参观目的" min-width="180" show-overflow-tooltip />
        <el-table-column prop="specialRequirements" label="特殊需求" min-width="180" show-overflow-tooltip />
        <el-table-column prop="organizerName" label="联系人姓名" width="120" />
        <el-table-column prop="groupType" label="联系人职务" width="120" />
        <el-table-column prop="organizerPhone" label="联系人电话" width="130" />
        <el-table-column prop="organizerEmail" label="联系人邮箱" width="130" />
        <el-table-column prop="createdTime" label="注册时间" width="130" />
        <el-table-column prop="status" label="状态" width="110">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'approved' ? 'success' : (scope.row.status === 'rejected' ? 'danger' : 'warning')">{{
                scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown>
              <el-button size="small" type="primary">
                审核
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleAudit(scope.row, 'approved')">通过</el-dropdown-item>
                  <el-dropdown-item @click="handleAudit(scope.row, 'rejected')">拒绝</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
          :page-size="size" :total="total" :current-page="current" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑' : '新增'" width="800px">
      <el-form :model="form" label-width="130px" ref="formRef">
        <el-form-item label="团体机构名称" required>
          <el-input v-model="form.groupName" />
        </el-form-item>
        <el-row :gutter="12">
          <el-col :span="12"><el-form-item label="预计参观人数" required><el-input
                v-model.number="form.groupSize" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="预计参观日期"><el-date-picker v-model="form.visitDate" type="date"
                value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
        </el-row>
        <el-form-item label="关注产品"><el-input type="textarea" :rows="2" v-model="form.visitPurpose"
            placeholder="请描述关注的产品类型..." /></el-form-item>
        <el-form-item label="参观目的"><el-input type="textarea" :rows="2" v-model="form.visitPurposeCheckout"
            placeholder="请描述参观目的..." /></el-form-item>
        <el-form-item label="特殊需求"><el-input type="textarea" :rows="2"
            v-model="form.specialRequirements" /></el-form-item>
        <el-row :gutter="12">
          <el-col :span="12"><el-form-item label="联系人姓名" required><el-input
                v-model="form.organizerName" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="联系人职务" required><el-input
                v-model="form.groupType" /></el-form-item></el-col>
        </el-row>
        <el-form-item label="联系人电话" required>
          <el-input v-model="form.organizerPhone" />
        </el-form-item>
        <el-form-item label="联系人邮箱">
          <el-input v-model="form.organizerEmail" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="pending">待审核</el-radio>
            <el-radio label="approved">已通过</el-radio>
            <el-radio label="rejected">已拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowDown } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useExcelExport } from '@/hooks/useExcelExport'

export default {
  name: 'AdminGroupVisit',
  components: { Plus, ArrowDown },
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const list = ref([])
    const total = ref(0)
    const current = ref(1)
    const size = ref(10)
    const keyword = ref('')
    const status = ref('')

    // 使用Excel导出hooks
    const { exportListData, columnWidthPresets, mapperPresets } = useExcelExport()

    const dialogVisible = ref(false)
    const formRef = ref(null)
    const form = reactive({
      id: null,
      groupName: '',
      organizerName: '',
      organizerPhone: '',
      organizerEmail: '',
      groupType: '',
      groupSize: null,
      visitDate: '',
      visitPurpose: '',
      visitPurposeCheckout: '',
      specialRequirements: '',
      status: 'pending'
    })

    const loadList = async () => {
      loading.value = true
      try {
        const params = { current: current.value, size: size.value }
        if (keyword.value) params.keyword = keyword.value
        if (status.value) params.status = status.value
        const res = await request.get('/admin/group-visit/page', { params })
        if (res && (res.code === '200' || res.code === 200)) {
          const data = res.data || {}
          list.value = data.records || []
          total.value = data.total || 0
        }
      } catch (e) {
        ElMessage.error('加载失败')
      } finally {
        loading.value = false
      }
    }

    const openEdit = (row) => {
      if (row) {
        Object.assign(form, row)
      } else {
        Object.assign(form, { id: null, groupName: '', organizerName: '', organizerPhone: '', organizerEmail: '', groupType: '', groupSize: null, visitDate: '', visitPurpose: '', visitPurposeCheckout: '', specialRequirements: '', status: 'pending' })
      }
      dialogVisible.value = true
    }

    const handleSave = async () => {
      // 验证必填字段
      const requiredFields = [
        { field: 'groupName', name: '团体机构名称' },
        { field: 'groupSize', name: '预计参观人数' },
        { field: 'organizerName', name: '联系人姓名' },
        { field: 'groupType', name: '联系人职务' },
        { field: 'organizerPhone', name: '联系人电话' }
      ]

      const missingFields = []
      for (const { field, name } of requiredFields) {
        if (!form[field] || (typeof form[field] === 'string' && form[field].trim() === '')) {
          missingFields.push(name)
        }
      }

      if (missingFields.length > 0) {
        ElMessage.error(`请填写必填字段：${missingFields.join('、')}`)
        return
      }

      // 验证人数必须是正整数
      if (form.groupSize && (form.groupSize <= 0 || !Number.isInteger(form.groupSize))) {
        ElMessage.error('预计参观人数必须是正整数')
        return
      }

      saving.value = true
      try {
        const api = form.id ? request.put : request.post
        const url = '/admin/group-visit'
        const res = await api(url, { ...form })
        if (res && (res.code === '200' || res.code === 200)) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          await loadList()
        } else {
          ElMessage.error(res?.msg || '保存失败')
        }
      } catch (e) {
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(`确定删除“${row.groupName}”吗？`, '确认', { type: 'warning' })
        const res = await request.delete(`/admin/group-visit/${row.id}`)
        if (res && (res.code === '200' || res.code === 200)) {
          ElMessage.success('删除成功')
          await loadList()
        } else {
          ElMessage.error(res?.msg || '删除失败')
        }
      } catch { }
    }

    const handleAudit = async (row, newStatus) => {
      try {
        const res = await request.put('/admin/group-visit/audit', null, { params: { id: row.id, status: newStatus, auditUser: 'admin' } })
        if (res && (res.code === '200' || res.code === 200)) {
          ElMessage.success('审核成功')
          await loadList()
        } else {
          ElMessage.error(res?.msg || '审核失败')
        }
      } catch (e) {
        ElMessage.error('审核失败')
      }
    }

    const handleSizeChange = (newSize) => {
      size.value = newSize
      current.value = 1 // 重置到第一页
      loadList()
    }

    const handleCurrentChange = (newCurrent) => {
      current.value = newCurrent
      loadList()
    }

    // 导出团体参观列表
    const exportExcel = async () => {
      // 获取数据的函数
      const fetchData = async () => {
        const params = { current: 1, size: 100000 }
        if (keyword.value) params.keyword = keyword.value
        if (status.value) params.status = status.value
        const res = await request.get('/admin/group-visit/page', { params })
        return res.data?.records || []
      }

      // 数据映射函数，对应团体参观信息的字段
      const mapData = (item) => ({
        '团体机构名称': mapperPresets.handleEmpty(item.groupName),
        '预计参观人数': mapperPresets.handleEmpty(item.groupSize),
        '预计参观日期': mapperPresets.handleEmpty(item.visitDate),
        '关注产品': mapperPresets.handleEmpty(item.visitPurpose),
        '参观目的': mapperPresets.handleEmpty(item.visitPurposeCheckout),
        '特殊需求': mapperPresets.handleEmpty(item.specialRequirements),
        '联系人姓名': mapperPresets.handleEmpty(item.organizerName),
        '联系人职务': mapperPresets.handleEmpty(item.groupType),
        '联系人电话': mapperPresets.handleEmpty(item.organizerPhone),
        '联系人邮箱': mapperPresets.handleEmpty(item.organizerEmail),
        '状态': getStatusText(item.status),
        '注册时间': mapperPresets.handleEmpty(item.createdTime),
      })

      // 自定义团体参观列表的列宽
      const groupVisitColumnWidths = [
        { wch: 25 }, // 团体机构名称
        { wch: 15 }, // 预计参观人数
        { wch: 15 }, // 预计参观日期
        { wch: 30 }, // 关注产品
        { wch: 30 }, // 参观目的
        { wch: 30 }, // 特殊需求
        { wch: 15 }, // 联系人姓名
        { wch: 15 }, // 联系人职务
        { wch: 15 }, // 联系人电话
        { wch: 25 }, // 联系人邮箱
        { wch: 12 },  // 状态
        { wch: 25 }, // 注册时间
      ]

      // 使用hooks进行导出
      await exportListData(
        fetchData,
        mapData,
        '团体参观列表',
        groupVisitColumnWidths,
        '团体参观列表'
      )
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已拒绝'
      }
      return statusMap[status] || status
    }

    onMounted(loadList)

    return { loading, saving, list, total, current, size, keyword, status, dialogVisible, formRef, form, loadList, openEdit, handleSave, handleDelete, handleAudit, handleSizeChange, handleCurrentChange, exportExcel }
  }
}
</script>

<style scoped>
.admin-group-visit {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
}

.pager {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>
